<template>
  <div class="role-add">
    <ElForm :model="roleData" label-width="auto" style="max-width: 600px">
      <ElFormItem label="角色名称">
        <ElInput v-model="roleData.name"></ElInput>
      </ElFormItem>
      <ElFormItem label="角色描述">
        <ElInput v-model="roleData.description"></ElInput>
      </ElFormItem>
      <ElFormItem label="是否是默认角色">
        <ElSwitch
          v-model="roleData.is_default"
          :active-value="'1'"
          :inactive-value="'0'"
        ></ElSwitch>
      </ElFormItem>
      <ElFormItem>
        <ElButton type="primary" @click="submitForm">提交</ElButton>
        <ElButton @click="handleReset">重置</ElButton>
      </ElFormItem>
    </ElForm>
  </div>
</template>
<script lang="ts" setup>
import { TRoleWithPage, useRoleStore } from "@/stores/role";
import { OperationType } from "@/utils/const";
import { PropType } from "vue";

const { proxy } = getCurrentInstance()!;

const defaultRoleData = {
  name: "",
  description: "",
  is_default: 0
};

const roleData = ref({
  name: "",
  description: "",
  is_default: 0
});

const roleStore = useRoleStore();

const { data, type } = defineProps({
  data: {
    type: Object as PropType<Partial<TRoleWithPage>>,
    default: () => ({})
  },
  type: {
    type: String,
    required: true
  }
});
const emit = defineEmits(["submit"]);
const submitForm = async () => {
  let params = { ...(data || {}), ...roleData.value } as TRoleWithPage;
  if (type === OperationType.ADD) {
    await roleStore.addRole(params);
    proxy?.$message.success("新增成功");
  } else if (type === OperationType.UPDATE) {
    await roleStore.updateRole(params);
    proxy?.$message.success("更新成功");
  }
  emit("submit");
};

const resetForm = () => {
  roleData.value =
    type === OperationType.ADD
      ? { ...roleData.value, ...defaultRoleData }
      : { ...roleData.value, ...data };
};
const handleReset = () => {
  resetForm();
};

watchEffect(() => {
  resetForm();
});
</script>
